package com.anjufang.service.system.impl;

import com.anjufang.entity.GroupDetail;
import com.anjufang.entity.GroupInfo;
import com.anjufang.entity.SourceUser;
import com.anjufang.mapper.SourceUserMapper;
import com.anjufang.service.system.SourceDataUserService;
import com.anjufang.utils.RSAEncryptDecrypt;
import com.anjufang.utils.Result;
import com.anjufang.utils.StringUtils;
import com.anjufang.utils.page.Query;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;


@Service
public class SourceDataUserServiceImpl implements SourceDataUserService {
	
	@Autowired
	private SourceUserMapper sourceUserMapper;


	@Override
	public List<SourceUser> queryList(Query query) {
		return sourceUserMapper.queryList(query);
	}

	@Override
	public int queryTotal(Query query) {
		return sourceUserMapper.queryTotal(query);
	}

	@Override
	public Result getByIdNumber(String idNumber,String userName) {
		if (StringUtils.isBlank(idNumber)) {
			return Result.error("身份证号码不能为空");
		}
		if (StringUtils.isBlank(userName)) {
			return Result.error("姓名不能为空");
		}
		try {
			System.out.println("加密后身份证："+idNumber);
			System.out.println("加密后姓名："+userName);
			idNumber = new String(RSAEncryptDecrypt.decrypt2(Base64.decodeBase64(idNumber.getBytes("UTF-8"))));
			userName = new String(RSAEncryptDecrypt.decrypt2(Base64.decodeBase64(userName.getBytes("UTF-8"))));
			System.out.println("解密后身份证："+idNumber);
			System.out.println("解密后姓名："+userName);
		} catch (Exception e) {
			e.printStackTrace();
			return Result.error("参数解码错误");
		}
		//查寻是否再用户表里
		SourceUser sourceUser = new SourceUser().selectOne(" id_number = {0} and user_name = {1} and is_deleted = {2}",idNumber,userName,0);
		if (null == sourceUser){
			return Result.error("抱歉，您没有参与资格,请检查姓名和身份证号码");
		}
		//判断是否开始分组
		List<GroupInfo> groupInfos = new GroupInfo().selectList(" is_deleted = {0}",0);
		if (CollectionUtils.isEmpty(groupInfos)) {
			return Result.error("活动还没开始，请稍后再来");
		}
		//如果在用户表查看是否已分组
		//查询分组详细表
		GroupDetail groupDetail = new GroupDetail().selectOne(" id_number={0} and is_deleted = {1}",idNumber, 0);
		if(null != groupDetail){
			GroupInfo groupInfo = new GroupInfo().selectById(groupDetail.getGroupId());
			if (groupInfo == null){
				return Result.error("获取抽签时间失败");
			}
			//说明已经分组
			return Result.ok("2").put("groupDetail",groupDetail).put("groupInfo",groupInfo);
		}
		return Result.ok("1").put("sourceUser",sourceUser);
	}
}

